<?php 
class Login extends CI_Controller {
	public function index(){
		$this->load->database();		
		// $this->load->view("welcome_message");
		// $this->load("input");
		$username = $this->input->post('username');
		$password = $this->input->post('password');
		$email = $this->input->post('email');
		$phoneNumber = $this->input->post('phoneNumber');

		// $countryCode = $this->input->post("countryCode");

		// echo "test\n";
		// echo "The Username is " . $username . ";\nThe phoneNumber is " . $phoneNumber . ";\nThe countryCode is " . $countryCode . ";\n";

		$this->output
	    ->set_content_type('application/json')
	    ->set_output(json_encode(array('userName' => $username, 'password' => $password, 'email' => $email, 'phoneNumber' => $phoneNumber)));   
	}

	public function accountRegister(){
		$this->load->database();		
		$username = $this->input->post('username');
		$password = $this->input->post('password');
		$email = $this->input->post('email');
		$phoneNumber = $this->input->post('phoneNumber');

		$data = array(
			'username' => $username,
			'password' => $password,
			'email' =>$email,
			'phoneNumber' => $phoneNumber);

		$this->db->insert('Users', $data);
		// $this->load->view("welcome_message");
		$this->output
	    ->set_content_type('application/json')
	    ->set_output(json_encode(array('success'=>true, 'username' => $username, 'password' => $password, 'email' => $email, 'phoneNumber' => $phoneNumber)));   	
	}

	public function verifyLogin(){
		$this->load->database();
		$username = $this->input->post('username');
		$password = $this->input->post('password');
		$this->db->select('userID, email, phoneNumber, updateTime');
		$this->db->where('username',$username);
		$this->db->where('password',$password);		
		//TODO: Ryan: can add LIMIT attribute to the SQL statement, to relieve the server work
		$this->db->from('Users');
		$query = $this->db->get();

		if ($query->num_rows() > 0) //Ryan: this verify it contains login information or not.
		{ //Ryan: Successful Login.
		   
			$firstRowResult = $query->row(0); //Get the first row of the result.
			$this->output
		    	->set_content_type('application/json')
				->set_output(json_encode(array('success'=>true, 'userID' => $firstRowResult->userID, 'email' => $firstRowResult->email, 'phoneNumber' => $firstRowResult->phoneNumber, 'updateTime' => $firstRowResult->updateTime)));   	

		} else { //Ryan: No data is found, i.e. User Auth Failed.
			$this->output
		    	->set_content_type('application/json')
				->set_output(json_encode(array('success'=>false, 'errorMsg' => 'Login Failed!')));   	
		}

	}
}
?>